package com.systop.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.systop.config.AlipayTemplate;
import com.systop.domain.vo.PayAsyncVo;
import com.systop.entity.GoodsStock;
import com.systop.entity.Order;
import com.systop.entity.StockLockDetail;
import com.systop.service.GoodsStockService;
import com.systop.service.OrderService;
import com.systop.service.StockLockDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @Description: TODO
 * @Author: jsj
 * @Date: 2023/3/25
 */
@Slf4j
@RestController
public class OrderPayedListener{

    @Autowired
    OrderService orderService;

    @Autowired
    GoodsStockService goodsStockService;

    @Autowired
    StockLockDetailService stockLockDetailService;

    @Autowired
    AlipayTemplate alipayTemplate;

    @PostMapping("/payed/notify")
    public String handleAliPayed(PayAsyncVo vo, HttpServletRequest request) throws AlipayApiException {

        System.out.println("执行支付完成方法");

        // Map<String, String[]> parameterMap = request.getParameterMap();
        // for (String key : parameterMap.keySet()) {
        //     String value = request.getParameter(key);
        //     System.out.println("参数名:"+key+"=====>"+value);
        // }

        //验签
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(), alipayTemplate.getCharset(), alipayTemplate.getSign_type()); //调用SDK验证签名

        if (signVerified){
            log.info("签名验证成功");
            //修改订单状态
            orderService.update(new UpdateWrapper<Order>().eq("order_no", vo.getOut_trade_no())
                    .set("order_status",1).set("modify_time", new Date()));
            //修改库存工作单状态
            stockLockDetailService.update(new UpdateWrapper<StockLockDetail>().eq("order_no", vo.getOut_trade_no())
                    .set("lock_status", 3));
            //更改库存量
            List<Order> orderList = orderService.list(new QueryWrapper<Order>().eq("order_no", vo.getOut_trade_no()));
            if(orderList!=null || orderList.size()>0){
                for (Order order : orderList) {
                    goodsStockService.update(new UpdateWrapper<GoodsStock>().eq("goods_id", order.getGoodsId())
                            .setSql("`stock_num` = `stock_num` - `lock_stock_num`,`lock_stock_num`=0"));
                }
            }
            return "success";
        }
        return "error";
    }
}
